package com.wangzemin.leetcode.num24;

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode preNode = null;
        ListNode firstNode = head;
        ListNode secondNode = head.next;
        head = secondNode;
        while (firstNode!=null&&secondNode != null) {
            ListNode secondNextNode = secondNode.next;
            secondNode.next = firstNode;
            firstNode.next = secondNextNode;
            if (preNode != null) {
                preNode.next = secondNode;
            }

            preNode = firstNode;
            firstNode = firstNode.next;
            if (firstNode!=null){
                secondNode = firstNode.next;
            }

        }

        return head;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        ListNode four = new ListNode(4);
        ListNode three = new ListNode(3,four);
        ListNode two = new ListNode(2,three);
        ListNode head = new ListNode(1,two);
        solution.swapPairs(head);
    }
}